package DataAccessObject;

import java.lang.reflect.ParameterizedType;

public abstract class DAO<K, E> {

	protected Class<E> entityClass;
	public Connection conexion;
	 
	@SuppressWarnings("unchecked")
	public DAO() throws Exception {
		ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();		
		this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[1];
		conexion = new Connection();
	}// Constructor
	 
	public void persist(E entity) { 
		try {
      conexion.open();
      conexion.kem.persist(entity);
      conexion.kem.getTransaction().commit();
    } catch (Exception e) {
      if (conexion.kem.getTransaction().isActive())
        conexion.kem.getTransaction().rollback();
      e.printStackTrace();
    } finally {
      conexion.close();
    }// try-catch
  }// persist
	
	public E remove(K id) {
	  E entity = null;
	  try {
      conexion.open();
       entity = conexion.kem.find(entityClass, id);
      conexion.kem.remove(entity);
      conexion.kem.getTransaction().commit();
    } catch (Exception e) {
      if (conexion.kem.getTransaction().isActive())
        conexion.kem.getTransaction().rollback();
      e.printStackTrace();
    } finally {
      conexion.close();
    }// try-catch
	  return entity;
  }// remove
	 
	public void merge(E entity) {
    try {
      conexion.open();
			conexion.kem.merge(entity);
			conexion.kem.getTransaction().commit();
		} catch (Exception e) {
		  if (conexion.kem.getTransaction().isActive())
		    conexion.kem.getTransaction().rollback();
			e.printStackTrace();
		} finally {
			conexion.close();
		}// try-catch
	}// merge
	 
	public E findById(K id) {
    E entity = null;
    try {
      conexion.newSession();
      entity = conexion.kem.find(entityClass, id);
    } finally {
      conexion.close();
    }// try-catch
    return entity;
	}// findById

}// class DAO
